﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Group
{
    /// <summary>列出User目前參與的聊天群組 (機器人Service用)</summary>

    public class robot_list_user_groups : IHttpHandler
    {
        private static List<string> kAllowServices = new List<string>() {
      "LoginiSenderWeb" };


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】檢查呼叫端的 IP Address 是否合法
                //
                string ipAddr = ChrisKit.getIPAddress(req);
                if (!RobotKit.isAllowRobotIP(ipAddr))
                {
                    throw new Exception("ERROR_01: Access Denied");//拒絕存取
                }


                //【02】取得POST參數，驗證身分
                //
                string SERVICE_ID = req.Form["SERVICE_ID"];//機器人服務ID
                string Password = req.Form["Password"];    //機器人服務密碼
                string SIP_Num = req.Form["SIP_Num"];//User的SIP帳號

                RobotServiceInfo rService = RobotKit.getServiceInfo(SERVICE_ID, Password);
                if (rService == null)
                {
                    throw new Exception("ERROR_02: Service Authentication Failed");//服務認證失敗
                }

                if (!kAllowServices.Contains(rService.SERVICE_ID))
                {
                    throw new Exception("ERROR_03: Service cannot access");//服務禁止存取
                }


                //【03】取得User目前參與的聊天群組
                //
                Dictionary<string, string>[] groupArray = OracleKitGroup.getUserGroups(SIP_Num);


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(groupArray);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
